{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你可以使用Python编写一个脚本来实现这个功能。以下是一个示例脚本，它接受源文件夹和导出目录作为输入，\n",
    "然后将文件名中 monster_ 与 _ 之间的序号提取出来，并创建相应的文件夹，将文件复制到对应的文件夹中，最后将这些文件夹移动到导出目录。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import shutil\n",
    "import re\n",
    "# 你可以使用Python编写一个脚本来实现这个功能。以下是一个示例脚本，它接受源文件夹和导出目录作为输入，\n",
    "# 然后将文件名中 monster_ 与 _ 之间的序号提取出来，并创建相应的文件夹，将文件复制到对应的文件夹中，最后将这些文件夹移动到导出目录。\n",
    "def process_files(source_dir, export_dir):\n",
    "    print('输入:'+source_dir)\n",
    "    print('输出:'+export_dir)\n",
    "    # 确保导出目录存在\n",
    "    if not os.path.exists(export_dir):\n",
    "        os.makedirs(export_dir)\n",
    "    qianzui_name = 'monster_'\n",
    "    # 遍历源文件夹中的所有文件\n",
    "    for filename in os.listdir(source_dir):\n",
    "        file_path = os.path.join(source_dir, filename)\n",
    "        \n",
    "        # 确保是文件而不是目录\n",
    "        if os.path.isfile(file_path):\n",
    "            # 使用正则表达式匹配文件名中的序号\n",
    "            match = re.search(r'qianzui_name(\\d+)_', filename)\n",
    "            if match:\n",
    "                folder_name = match.group(1)  # 获取匹配的序号\n",
    "                # if folder_name > 20000:\n",
    "                dest_folder = os.path.join(export_dir, folder_name)\n",
    "                \n",
    "                # 确保目标文件夹存在\n",
    "                if not os.path.exists(dest_folder):\n",
    "                    os.makedirs(dest_folder)\n",
    "                \n",
    "                # 复制文件到目标文件夹\n",
    "                shutil.copy(file_path, dest_folder)\n",
    "                print(f\"Copied {file_path} to {dest_folder}\")\n",
    "            else:\n",
    "                print(f\"No match found for {filename}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # 输入源文件夹和导出目录\n",
    "    source_folder = input(\"请输入源文件夹路径: \")\n",
    "    export_folder = input(\"请输入导出目录路径: \")\n",
    "    # export_folder = input(\"请输入导出目录路径: \")\n",
    "    \n",
    "    # 处理文件\n",
    "    process_files(source_folder, export_folder)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "读取文本内容进行,按id剔除资源"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入:C:\\Users\\Public\\Nwt\\cache\\recv\\王鑫\\火牛传奇\\客户端\\dev\\anim\\npc\n",
      "输出:c:\\Users\\Administrator\\Desktop\\ceshi11\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import shutil\n",
    "import re\n",
    "# 你可以使用Python编写一个脚本来实现这个功能。以下是一个示例脚本，它接受源文件夹和导出目录作为输入，\n",
    "# 然后将文件名中 monster_ 与 _ 之间的序号提取出来，并创建相应的文件夹，将文件复制到对应的文件夹中，最后将这些文件夹移动到导出目录。\n",
    "def process_files(prefix,input_file,source_dir, export_dir):\n",
    "    print('输入:'+source_dir)\n",
    "    print('输出:'+export_dir)\n",
    "    # 确保导出目录存在\n",
    "    if not os.path.exists(export_dir):\n",
    "        os.makedirs(export_dir)\n",
    "   # 读取文本文件\n",
    "    with open(input_file, 'r', encoding='utf-8') as file:\n",
    "        lines = file.readlines()\n",
    "    \n",
    "    # 提取文件名（不包含后缀）\n",
    "    file_names = [line.strip() for line in lines if line.strip()]\n",
    "\n",
    "    # qianzui_name = 'npc_'\n",
    "    # 遍历源文件夹中的所有文件\n",
    "    for filename in os.listdir(source_dir):\n",
    "        file_path = os.path.join(source_dir, filename)\n",
    "\n",
    "        \n",
    "        # 确保是文件而不是目录\n",
    "        if os.path.isfile(file_path):\n",
    "            # 使用正则表达式匹配文件名中的序号\n",
    "            match = re.search(r'{}(\\d+)_'.format(prefix), filename)\n",
    "            if match:\n",
    "                folder_name = match.group(1)  # 获取匹配的序号\n",
    "                # if folder_name in \n",
    "                # if folder_name > 20000:\n",
    "                # 获取文件名和扩展名\n",
    "                # print('folder_name:',folder_name,str(int(folder_name)))\n",
    "                # return\n",
    "                base_name, ext = os.path.splitext(file_path)\n",
    "                # print('folder_name:',base_name, ext)\n",
    "                # 检查文件名是否在文本文件中\n",
    "                # value = str(int(folder_name))\n",
    "                # if value and value in file_names:\n",
    "                if folder_name in file_names:\n",
    "                    # 检查文件是否为 .png 或 .plist\n",
    "                    if ext in ['.png', '.plist']:\n",
    "                        # dest_folder = os.path.join(export_dir, folder_name)\n",
    "                        # # 确保目标文件夹存在\n",
    "                        # if not os.path.exists(dest_folder):\n",
    "                        #     os.makedirs(dest_folder)\n",
    "\n",
    "                        # 构建输出路径\n",
    "                        # new_file_path = os.path.join(export_dir, file)\n",
    "                        # print('folder_name:',base_name, ext)\n",
    "                        # 移动文件\n",
    "                        export_filepath = os.path.join(export_dir, filename)\n",
    "                        shutil.move(file_path, export_filepath)\n",
    "                        print(f\"Moved: {file_path} to {export_filepath}\")  \n",
    "                        # # # 复制文件到目标文件夹\n",
    "                        # shutil.copy(file_path, export_dir)\n",
    "                        # print(f\"Copied {file_path} to {dest_folder}\")\n",
    "            else:\n",
    "                print(f\"No match found for {filename}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # 输入源文件夹和导出目录\n",
    "    file_name = r'c:\\Users\\Administrator\\Desktop\\delid.txt'\n",
    "    # source_folder = input(\"请输入源文件夹路径: \")\n",
    "    # export_folder = input(\"请输入导出目录路径: \")\n",
    "    source_folder = r'C:\\Users\\Public\\Nwt\\cache\\recv\\王鑫\\火牛传奇\\客户端\\dev\\anim\\npc'#input(\"请输入源文件夹路径: \")\n",
    "    export_folder = r'c:\\Users\\Administrator\\Desktop\\ceshi11'\n",
    "\n",
    "    # export_folder = input(\"请输入导出目录路径: \")\n",
    "    \n",
    "    # 处理文件\n",
    "    process_files( 'npc_',file_name,source_folder, export_folder)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "遍历文件将文件名以\"|\"符号连接"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "发生错误: [WinError 3] 系统找不到指定的路径。: ''\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "def list_files_to_text(folder_path, output_file_path):\n",
    "    try:\n",
    "        # 获取文件夹下所有文件的名字\n",
    "        file_names = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]\n",
    "        \n",
    "        # 将文件名以 \"|\" 符号连接成一个字符串\n",
    "        file_names_str = \"|\".join(file_names)\n",
    "        \n",
    "        # 将字符串写入到指定的文本文件中\n",
    "        with open(output_file_path, 'w', encoding='utf-8') as file:\n",
    "            file.write(file_names_str)\n",
    "        \n",
    "        print(f\"文件名已成功写入到 {output_file_path}\")\n",
    "    \n",
    "    except Exception as e:\n",
    "        print(f\"发生错误: {e}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # 示例文件夹路径（你可以修改为你实际的文件夹路径）\n",
    "    folder_path = input(\"请输入文件夹路径: \")\n",
    "    \n",
    "    # 获取桌面路径\n",
    "    desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')\n",
    "    \n",
    "    # 指定输出文件路径\n",
    "    output_file_path = os.path.join(desktop_path, 'file_names.txt')\n",
    "    \n",
    "    # 调用函数\n",
    "    list_files_to_text(folder_path, output_file_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "测试功能"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "<>:1: SyntaxWarning: invalid escape sequence '\\w'\n",
      "<>:1: SyntaxWarning: invalid escape sequence '\\w'\n",
      "C:\\Users\\Administrator\\AppData\\Local\\Temp\\ipykernel_31404\\77902194.py:1: SyntaxWarning: invalid escape sequence '\\w'\n",
      "  folder_path='E:\\work\\cq1_client\\Client\\dev\\alg\\dev\\config'\n",
      "C:\\Users\\Administrator\\AppData\\Local\\Temp\\ipykernel_31404\\77902194.py:1: SyntaxWarning: invalid escape sequence '\\w'\n",
      "  folder_path='E:\\work\\cq1_client\\Client\\dev\\alg\\dev\\config'\n"
     ]
    },
    {
     "ename": "OSError",
     "evalue": "[WinError 123] 文件名、目录名或卷标语法不正确。: 'E:\\\\work\\\\cq1_client\\\\Client\\\\dev\\x07lg\\\\dev\\\\config'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mOSError\u001b[0m                                   Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[3], line 2\u001b[0m\n\u001b[0;32m      1\u001b[0m folder_path\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mE:\u001b[39m\u001b[38;5;124m\\\u001b[39m\u001b[38;5;124mwork\u001b[39m\u001b[38;5;124m\\\u001b[39m\u001b[38;5;124mcq1_client\u001b[39m\u001b[38;5;124m\\\u001b[39m\u001b[38;5;124mClient\u001b[39m\u001b[38;5;124m\\\u001b[39m\u001b[38;5;124mdev\u001b[39m\u001b[38;5;130;01m\\a\u001b[39;00m\u001b[38;5;124mlg\u001b[39m\u001b[38;5;124m\\\u001b[39m\u001b[38;5;124mdev\u001b[39m\u001b[38;5;124m\\\u001b[39m\u001b[38;5;124mconfig\u001b[39m\u001b[38;5;124m'\u001b[39m\n\u001b[1;32m----> 2\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m f \u001b[38;5;129;01min\u001b[39;00m \u001b[43mos\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mlistdir\u001b[49m\u001b[43m(\u001b[49m\u001b[43mfolder_path\u001b[49m\u001b[43m)\u001b[49m:\n\u001b[0;32m      3\u001b[0m     \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mpath:\u001b[39m\u001b[38;5;124m'\u001b[39m,f)\n",
      "\u001b[1;31mOSError\u001b[0m: [WinError 123] 文件名、目录名或卷标语法不正确。: 'E:\\\\work\\\\cq1_client\\\\Client\\\\dev\\x07lg\\\\dev\\\\config'"
     ]
    }
   ],
   "source": [
    "folder_path='E:\\work\\cq1_client\\Client\\dev\\alg\\dev\\config'\n",
    "for f in os.listdir(folder_path):\n",
    "    print('path:',f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "地图配置生成+需要搭配csv转lua表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "匹配结果已成功写入到 C:\\Users\\Administrator\\Desktop\\extracted_chars.txt\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import re\n",
    "\n",
    "def extract_chars_to_text(input_file_path, output_file_path, encoding='utf-8'):\n",
    "    try:\n",
    "        # 正则表达式模式，匹配 '['、']' 和 '|' 字符\n",
    "        # pattern = r'\\[.*?\\|'\n",
    "        # pattern=r'\\[([^| ]*?)(?:\\|| )'\n",
    "        pattern=r'\\[([^|\\s\\t]+)(?=[|\\s\\t]|\\]|$)'\n",
    "        # 用于存储匹配结果的列表\n",
    "        matches = []\n",
    "        \n",
    "        # 读取输入文件，指定编码\n",
    "        with open(input_file_path, 'r', encoding=encoding) as file:\n",
    "            for line in file:\n",
    "                # 查找所有匹配项\n",
    "                for match in re.findall(pattern, line):\n",
    "                    # 添加到结果列表中（避免重复可以使用集合 set，但这里保持列表形式）\n",
    "                    if match not in matches:  # 可选：避免重复项\n",
    "                        matches.append(match)\n",
    "        \n",
    "        # 将匹配结果用 '|' 符号连接成一个字符串\n",
    "        matches_str = \"|\".join(matches)\n",
    "        \n",
    "        # 将字符串写入到指定的输出文件中\n",
    "        with open(output_file_path, 'w', encoding='utf-8') as file:\n",
    "            file.write(matches_str)\n",
    "        \n",
    "        print(f\"匹配结果已成功写入到 {output_file_path}\")\n",
    "    \n",
    "    except Exception as e:\n",
    "        print(f\"发生错误: {e}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # 输入文件路径（你可以修改为你实际的文件路径）\n",
    "    input_file_path = input(\"请输入输入文件路径: \")\n",
    "    \n",
    "    # 获取桌面路径\n",
    "    desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')  # 跨平台获取桌面路径\n",
    "    \n",
    "    # 指定输出文件路径\n",
    "    output_file_path = os.path.join(desktop_path, 'extracted_chars.txt')\n",
    "    \n",
    "    # 输入文件编码（默认为 'utf-8'，如果不是请修改）\n",
    "    encoding = 'gbk'#input(\"请输入文件编码（如不确定，可尝试 'utf-8', 'gbk', 'gb2312' 等）: \") or 'utf-8'\n",
    "    \n",
    "    # 调用函数\n",
    "    extract_chars_to_text(input_file_path, output_file_path, encoding)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "读取cfg_model_info.xls表将内容复制到另一张表中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "处理完成，结果已保存到 c:\\Users\\Administrator\\Desktop\\aaa\\cfg_model_info.xls\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# 读取Excel文件\n",
    "# file_a = r'c:\\Users\\Administrator\\Desktop\\ccc33\\cfg_model_infoA.xls'\n",
    "# file_b = r'c:\\Users\\Administrator\\Desktop\\ccc33\\cfg_model_infoB.xls'\n",
    "# file_C = r'c:\\Users\\Administrator\\Desktop\\ccc33\\cfg_model_info.xls'\n",
    "\n",
    "file_a = r'c:\\Users\\Administrator\\Desktop\\aaa\\cfg_model_infoA.xls'\n",
    "file_b = r'c:\\Users\\Administrator\\Desktop\\aaa\\cfg_model_infoB.xls'\n",
    "file_C = r'c:\\Users\\Administrator\\Desktop\\aaa\\cfg_model_info.xls'\n",
    "\n",
    "\n",
    "# 读取表格A和表格B\n",
    "df_a = pd.read_excel(file_a, header=1)\n",
    "df_b = pd.read_excel(file_b, header=1)\n",
    "# # 遍历表格A的每一行\n",
    "# for _, row_a in df_a.iterrows():\n",
    "#      # 遍历表格B的每一行\n",
    "#     for _, row_b in df_b.iterrows():\n",
    "#         if row_a['id'] == row_b['id'] and :\n",
    "#             print(row_a['id'])\n",
    "#             print(row_b['id'])\n",
    "\n",
    " \n",
    "# 找出表格B中id和type字段与表格A相同的行\n",
    "# 假设id和type字段在表格A和表格B中都是前两列（如果不是，请调整）\n",
    "merged_df = pd.merge(df_b, df_a[['id', 'type']], on=['id', 'type'], how='inner')\n",
    " \n",
    "# 将表格C的前三行直接复制（假设前三行是标题或表头信息，从表格A复制）\n",
    "# 假设表格A的前三行是我们想要的表头信息\n",
    "# original_columns = df_a.columns.tolist()\n",
    "header_df = df_a.iloc[:3, :]\n",
    " \n",
    "# 合并表头信息和匹配的行\n",
    "df_c = pd.concat([header_df, merged_df.iloc[3:, :]], ignore_index=True)  # 跳过表格A的前三行表头\n",
    " \n",
    "# 将表格C中首列数据递增+1\n",
    "# 假设首列是'id'列（如果不是，请调整）\n",
    "# df_c['//唯一ID'] = df_c['//唯一ID'].astype(int) + 1\n",
    "for i in range(3, len(df_c)):\n",
    "    df_c.at[i, '///index'] = i\n",
    " \n",
    "# 将结果保存到新的Excel文件\n",
    "# output_file = 'cfg_model_info.xlsx'\n",
    "output_file = file_C\n",
    "# with pd.ExcelWriter(output_file, engine='openpyxl') as writer:\n",
    "# with pd.ExcelWriter(output_file, engine='xlwt') as writer:\n",
    "with pd.ExcelWriter(output_file, engine='xlsxwriter')as writer:\n",
    "    df_c.to_excel(writer, index=False,sheet_name='cfg_model_info')\n",
    "\n",
    "# writer._save()\n",
    "#！！！！！！！！！！！资源调整 文件占用报错 看下面\n",
    "#！！！！！！！！导出excel97-2003格式 xsl文件需要 pip install xlwt\n",
    "#！！！！！！！！导出excel97-2003格式 xsl文件需要 pip install XlsxWriter\n",
    "#！！！！！！！以上都没有就用wps另存一下xsl格式\n",
    "print(f\"处理完成，结果已保存到 {output_file}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "work996",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
